package com.tycmc.signelectroniccontracts.logic.read;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.tycmc.signelectroniccontracts.act.read.ActReadPDF;
import com.tycmc.signelectroniccontracts.entity.HtEntity;
import com.tycmc.signelectroniccontracts.entity.PDFPositionEntity;
import com.tycmc.signelectroniccontracts.entity.QianYueEntity;
import com.tycmc.signelectroniccontracts.tools.base.LogicParent;
import com.tycmc.signelectroniccontracts.tools.images.ToolFile;
import com.tycmc.signelectroniccontracts.tools.net.NetUrl;
import com.tycmc.signelectroniccontracts.tools.net.NetWorkUtils;
import com.tycmc.signelectroniccontracts.tools.net.RequestAction;
import com.tycmc.signelectroniccontracts.tools.net.result.DownResult;
import com.tycmc.signelectroniccontracts.tools.net.result.DownResultPDF;
import com.tycmc.signelectroniccontracts.tools.net.result.NetworkResult;
import com.tycmc.signelectroniccontracts.tools.net.result.ProGressUpDataListen;
import com.tycmc.signelectroniccontracts.tools.other.TextShow;
import com.tycmc.signelectroniccontracts.tools.other.TyTypenum;
import com.tycmc.signelectroniccontracts.tools.permissions.PermissionsTool;
import com.tycmc.signelectroniccontracts.tools.show.LogShow;
import com.tycmc.signelectroniccontracts.tools.show.ProDialog;
import com.tycmc.signelectroniccontracts.tools.show.ToastShow;
import com.tycmc.signelectroniccontracts.tools.store.DBHelper;
import com.tycmc.signelectroniccontracts.tools.store.FileStore;
import com.tycmc.signelectroniccontracts.tools.store.SharePre;
import com.tycmc.signelectroniccontracts.tools.store.SharePreName;
import com.tycmc.signelectroniccontracts.ui.PopQianMing;
import com.tycmc.signelectroniccontracts.ui.PopQianyue;
import com.tycmc.signelectroniccontracts.ui.PopYanZhengma;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class PreReadPDF extends LogicParent {
    private long timelong = 30 * 60 * 1000;
    private HtEntity.SubContractListEntity entity;
    private ActReadPDF context;
    private ReadPDFInterface pre;
    private String contractNo;
    private String subContractNo;
    private boolean isRead = true;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            handler.sendEmptyMessageDelayed(msg.what - 1, 1000);
            pre.daojishi(msg.what);
            return false;
        }
    });

    public PreReadPDF(ReadPDFInterface pre, Intent intent) {
        this.pre = pre;
        context = ((ActReadPDF) pre);
        contractNo = intent.getStringExtra("contractNo");
        subContractNo = intent.getStringExtra("subContractNo");
        entity = ((HtEntity.SubContractListEntity) intent.getSerializableExtra("entity"));
        pre.yiqianyue(entity.getSignStatusID().equals("1"));
        pre.yiyuedu(entity.getPdfReadState().equals("1"));
        isRead = !entity.getPdfReadState().equals("1");
    }


    public void getQianyueLiebiao(final View v) {
        RequestAction action = new RequestAction(NetUrl.queryVoucherByBusinessCode);
        action.putBody("businessCode", SharePre.getString(SharePreName.businessCode, ""));
        action.putBody("clientArchiveNo", SharePre.getString(SharePreName.clientArchiveNo, ""));
        final ProDialog dialog = new ProDialog(context, "正在加载签约列表");
        dialog.show();
        new NetWorkUtils(context).postJson(action, new NetworkResult() {
            @Override
            public void sucess(Map<String, Object> data, String str) {
                dialog.dismiss();
                final List<QianYueEntity> list = new ArrayList<>();
                if (data.get("data") instanceof List) {
                    List<Map> mapList = (List<Map>) data.get("data");
                    for (int i = 0; i < mapList.size(); i++) {
                        Map map = mapList.get(i);
                        QianYueEntity entity = new QianYueEntity();
                        entity.setAttaID(TextShow.valueOf(map.get("attaID")));
                        entity.setAttaPath(TextShow.valueOf(map.get("attaPath")));
                        entity.setBusinessCode(TextShow.valueOf(map.get("businessCode")));
                        entity.setCreateTime(TextShow.valueOf(map.get("createTime")));
                        entity.setDisplayName(TextShow.valueOf(map.get("displayName")));
                        list.add(entity);
                    }
                }
                if (list.size() == 0) {
                    ToastShow.popupToast("当前用户无签章，请联系管理员");
                    return;
                }
                if (System.currentTimeMillis() - SharePre.getLong(SharePreName.sendMSgTime, 0) > timelong) {
                    PopYanZhengma popYanZhengma = new PopYanZhengma(context, new PopYanZhengma.YanZhengMaInter() {
                        @Override
                        public void codeShow(String code) {
                            context.hideSoftInputView();
                            SharePre.getEditor().putLong(SharePreName.sendMSgTime, System.currentTimeMillis()).commit();
                            PopQianyue popQianyue = new PopQianyue(context, list, new PopQianyue.QianYueInterface() {
                                @Override
                                public void queyue(QianYueEntity entity) {
                                    uplodadQiqnyue(entity);
                                }
                            });
                            popQianyue.show(v);
                        }
                    }, contractNo, subContractNo);
                    popYanZhengma.show(v);
                } else {
                    PopQianyue popQianyue = new PopQianyue(context, list, new PopQianyue.QianYueInterface() {
                        @Override
                        public void queyue(QianYueEntity entity) {
                            uplodadQiqnyue(entity);
                        }
                    });
                    popQianyue.show(v);
                }

            }

            @Override
            public void failed(Object data) {
                dialog.dismiss();
                ToastShow.popupToast(data + "");
            }
        });
    }

    /**
     * 法人签约
     *
     * @param entity
     */
    private void uplodadQiqnyue(QianYueEntity entity) {
        RequestAction action = new RequestAction(NetUrl.pdfSignLegalPersonal);
        action.putBody("clientSignatureID", entity.getAttaID());
        action.putBody("subContractNo", subContractNo);
        final ProDialog dialog = new ProDialog(context, "");
        dialog.show();
        new NetWorkUtils(context).postJson(action, new NetworkResult() {
            @Override
            public void sucess(Map<String, Object> data, String str) {
                dialog.dismiss();
                ToastShow.popupToast("签约成功");
                pre.yiqianyue(false);
            }

            @Override
            public void failed(Object data) {
                dialog.dismiss();
            }
        });
    }

    public void onrefresh(String urlPath) {
        DBHelper.delete(context, urlPath.hashCode() + "");
        initReadPDf(urlPath);
    }

    public void initData(String urlPath) {
        List<PDFPositionEntity> quary = DBHelper.quary(context, urlPath.hashCode() + "");
        if (quary == null || quary.size() == 0) {
            initReadPDf(urlPath);
        } else {
            List<byte[]> list = new ArrayList<>();
            for (int i = 0; i < quary.size(); i++) {
                PDFPositionEntity entity = quary.get(i);
                if (new File(entity.getUrlpath()).exists()) {
                    try {
                        list.add(ToolFile.readStream(entity.getUrlpath()));

                    } catch (Exception e) {
                        DBHelper.delete(context, urlPath.hashCode() + "");
                        initReadPDf(urlPath);
                        return;
                    }
                } else {
                    DBHelper.delete(context, urlPath.hashCode() + "");
                    initReadPDf(urlPath);
                    return;
                }
            }
            pre.initbytes(ToolFile.byteMergerAll(list));
        }
    }

    private void initReadPDf(final String urlPath) {
        PermissionsTool.requestPermiss(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionsTool.PerMissionCallBack() {
            @Override
            public void permissIsPass(String[] permission, boolean isPass) {
                if (isPass) {
                    downPDF(urlPath);
                } else {

                }
            }
        }, context);

    }

    public void downPDF(String url) {
        RequestAction requestAction = new RequestAction(url);
        final ProDialog dialog = new ProDialog(context, "");
        dialog.show();
        new NetWorkUtils(context).downLoadPDF(requestAction, new DownResultPDF() {
            @Override
            public void downsucess(long current, long total, boolean flag) {

            }

            @Override
            public void downfail(Object error) {
                dialog.dismiss();
            }

            @Override
            public void sucess(File[] file) {
                dialog.dismiss();
                try {
                    List<byte[]> list = new ArrayList<>();
                    for (int i = 0; i < file.length; i++) {
                        list.add(ToolFile.readStream(file[i].getAbsolutePath()));
                    }
                    byte[] bytes = ToolFile.byteMergerAll(list);

                    pre.initbytes(bytes);

                } catch (Exception e) {
                    LogShow.i("成功错误日志", e.getMessage());
                    pre.initbytes(e.getMessage().getBytes());
                    e.printStackTrace();
                }
            }
        });
    }

    public void downPDF1(String url) {
        RequestAction requestAction = new RequestAction(url);
        final ProDialog dialog = new ProDialog(context, "");
        dialog.show();
        new NetWorkUtils(context).downLoadFile1(requestAction, new DownResult() {
            @Override
            public void downsucess(long current, long total, boolean flag) {

            }

            @Override
            public void downfail(Object error) {

            }

            @Override
            public void sucess(File file) {
                    pre.initPDFUrl(file);
            }
        });
    }



    private void upload(String path) {
        RequestAction action = new RequestAction(NetUrl.pdfSignPersonal);
        action.putBody("subContractNo", subContractNo);
        action.putBody("uploadFile", new File(path));
        final ProDialog dialog = new ProDialog(context, "正在签章");
        dialog.show();
        new NetWorkUtils(context).upLoadProgress(action, new ProGressUpDataListen() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {

            }

            @Override
            public void sucess(Map<String, Object> data, String str) {
                dialog.dismiss();
                ToastShow.popupToast("签章成功");
                pre.onrefrsh();
                pre.yiqianyue(false);
            }

            @Override
            public void failed(Object data) {
                dialog.dismiss();
                ToastShow.popupToast(data.toString());
            }
        });
    }

    public void getCode(final View v) {
        if (System.currentTimeMillis() - SharePre.getLong(SharePreName.sendMSgTime, 0) > timelong) {
            PopYanZhengma popYanZhengma = new PopYanZhengma(context, new PopYanZhengma.YanZhengMaInter() {
                @Override
                public void codeShow(String code) {
                    SharePre.getEditor().putLong(SharePreName.sendMSgTime, System.currentTimeMillis()).commit();
                    context.hideSoftInputView();
                    PopQianMing popQianMing = new PopQianMing(context, new PopQianMing.QianMingInterface() {
                        @Override
                        public void qianMing(Bitmap bitmap, String path) {
                            upload(path);
                        }
                    });
                    popQianMing.show(v);
                }
            }, contractNo, subContractNo);
            popYanZhengma.show(v);
        } else {
            PopQianMing popQianMing = new PopQianMing(context, new PopQianMing.QianMingInterface() {
                @Override
                public void qianMing(Bitmap bitmap, String path) {
                    upload(path);
                }
            });
            popQianMing.show(v);
        }

    }

    public void ondeStory() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }

    public void first() {
        if (isRead) {
            if (handler != null) {
                isRead = false;
                handler.sendEmptyMessage(10);
            }
        }

    }

    /**
     * 已读
     */
    public void yidu() {
        pre.yiyuedu(true);//已阅读
        TyTypenum.isQianyue = true;
        RequestAction action = new RequestAction(NetUrl.alreadyReadPdf);
        action.putBody("subContractNo", subContractNo);
        new NetWorkUtils(context).postJson(action, new NetworkResult() {
            @Override
            public void sucess(Map<String, Object> data, String str) {

            }

            @Override
            public void failed(Object data) {

            }
        });
    }


    public interface ReadPDFInterface {
        void initbytes(byte[] urlPath);

        void daojishi(int what);


        void yiqianyue(boolean isVisible);//是否签章成功

        void yiyuedu(boolean isyueedu);//已阅读
        void onrefrsh();
        void initPDFUrl(File urlPath);
    }
}
